package com.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;

@Component
public class SendEMailUtils {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    private static final String VALIDATE_CODE="验证码";
    private static final String TEXT="你的书评网验证码是";

    public Boolean sendMail(String mailAddress,int validateCode){
        try {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            String as = new InternetAddress(MimeUtility.encodeText("随意") + "<" + from + ">").toString();
            simpleMailMessage.setFrom(as);
        simpleMailMessage.setTo(mailAddress);
        simpleMailMessage.setSubject(VALIDATE_CODE);
        simpleMailMessage.setText(TEXT+validateCode);
        javaMailSender.send(simpleMailMessage);
        return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
